package com.gutsyzhan.bilibili.service.impl;

import com.gutsyzhan.bilibili.dao.FileDao;
import com.gutsyzhan.bilibili.domain.File;
import com.gutsyzhan.bilibili.service.FileService;
import com.gutsyzhan.bilibili.util.FastDFSUtil;
import com.gutsyzhan.bilibili.util.MD5Util;
import com.mysql.jdbc.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private FileDao fileDao;

    @Resource
    private FastDFSUtil fastDFSUtil;

    @Override
    public String uploadFileBySlices(MultipartFile slice, String fileMd5, Integer sliceNo, Integer totalSliceNo) throws Exception {
        //1、先从数据库中通过md5字符串查询文件是否已经上传过，注意is_delete为1表示文件实际上被删除了
        File dbFileByMd5 = fileDao.getFileByMd5(fileMd5);
        if(null != dbFileByMd5){
            return dbFileByMd5.getUrl();
        }
        //2、上传文件至FastDFS
        String url = fastDFSUtil.uploadFileBySlices(slice, fileMd5, sliceNo, totalSliceNo);
        if(!StringUtils.isNullOrEmpty(url)){
            //文件上传成功，保存文件信息至数据库
            dbFileByMd5 = new File();
            dbFileByMd5.setCreateTime(new Date());
            dbFileByMd5.setMd5(fileMd5);
            dbFileByMd5.setUrl(url);
            dbFileByMd5.setType(fastDFSUtil.getFileType(slice));
            fileDao.addFile(dbFileByMd5);
        }
        return url;
    }

    @Override
    public String getFileMd5(MultipartFile file) throws Exception {
        return MD5Util.getFileMD5(file);
    }
}
